﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;

namespace Bricks.BaseFramework.Utility
{
    /*********************************************************
    * 1.版权：积木工场 Bricks Factory
    * 2.作用：图片转换器（如路径转BitmapImage对象）
    * 3.创建人：罗泽新
    * 4.创建日期：2012-04-27
    * 5.最后修改人：罗泽新
    * 6.最后修改日期：2012-04-27
    * 7.修改项目：
    * *******************************************************/
    public class ImageConverter
    {
        /// <summary>
        /// BitmapImage转byte[]
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static byte[] ImageToByte(System.Windows.Media.Imaging.BitmapImage image)
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(image));
                encoder.Save(memStream);
                byte[] bytestream = memStream.GetBuffer();
                return bytestream;
            }
        }

        /// <summary>
        /// 读取图片路径，并将其转换为BitmapImage输出
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static BitmapImage ConvertToImage(string path)
        {
            if (!File.Exists(path))
                return null;

            BitmapImage result = new BitmapImage();
            string fileType = Path.GetExtension(path);  //扩展名

            //如果是emf文件，需要进行转换
            if (fileType.ToLower() == ".emf")
            {
                Bitmap bmp = new Bitmap(new Metafile(path));
                result = BitmapToBitmapImage(bmp);
            }
            else
            {
                result.BeginInit();
                result.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read);
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.EndInit();
                result.StreamSource.Dispose();
            }
            return result;
        }

        /// <summary>
        /// Bitmap转换为BitmapImage
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
        {
            Bitmap bitmapSource = new Bitmap(bitmap.Width, bitmap.Height);
            bitmapSource.MakeTransparent();
            int i, j;
            for (i = 0; i < bitmap.Width; i++)
                for (j = 0; j < bitmap.Height; j++)
                {
                    Color pixelColor = bitmap.GetPixel(i, j);
                    Color newColor = Color.FromArgb(pixelColor.R, pixelColor.G, pixelColor.B);
                    if (newColor == Color.FromArgb(255, 0, 0, 0))
                    {
                        newColor = Color.FromArgb(255, 255, 255, 255);
                    }
                    bitmapSource.SetPixel(i, j, newColor);
                }
            MemoryStream ms = new MemoryStream();
            bitmapSource.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(ms.ToArray());
            bitmapImage.EndInit();
            return bitmapImage;
        }

        /// <summary>
        /// 转换：可在WPF绑定图片时作为转换器使用
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || !(value is string))
                return null;
            var path = value as string;
            return ConvertToImage(path);
        }

        /// <summary>
        /// 回转：暂不实现
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
